package activity.live;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.callback.ICameraPlayStateCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import com.hichip.data.HiDeviceInfo;
import com.hichip.sdk.HiChipP2P;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import activity.live.fragment.FirstTabFragment;
import activity.live.fragment.SecondTabFrament;
import activity.live.fragment.VpAdapter;
import activity.setting.SettingActivity;
import base.HiLandScapeActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.HiDataValue;
import common.MyLiveViewGLMonitor;
import custom.SwitchButton;
import utils.AnimationProUtils;
import utils.HiToast;
import utils.HiTools;
import utils.SharePreUtils;
/**
 * Created by lt on 2017\12\29 0029.
 */
public class LiveViewActivity extends HiLandScapeActivity implements ICameraIOSessionCallback, ICameraPlayStateCallback, View.OnTouchListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    @BindView(R.id.live_monitor) public MyLiveViewGLMonitor mMonitor;
    @BindView(R.id.tv_video_quality) TextView tv_video_quality;
    @BindView(R.id.progressbar) ProgressBar progressbar;
    @BindView(R.id.rl_wrap) public RelativeLayout rl_wrap;
    @BindView(R.id.iv_recording) public ImageView iv_recording;
    @BindView(R.id.tv_record_time) public TextView tv_record_time;
    @BindView(R.id.ll_recording) public LinearLayout ll_recording;
    @BindView(R.id.ll_bottom) LinearLayout ll_bottom;
    @BindView(R.id.rl_landscape_view) public RelativeLayout rl_landscape_view;
    @BindView(R.id.iv_landscape_listen) public ImageView iv_landscape_listen;
    @BindView(R.id.iv_landscape_talk) public ImageView iv_landscape_talk;
    @BindView(R.id.tv_landscape_video_quality) TextView tv_landscape_video_quality;
    @BindView(R.id.btn_return) ImageView btn_return;
    @BindView(R.id.title_middle) TextView title_middle;
    @BindView(R.id.rl_title) RelativeLayout titleview;
    @BindView(R.id.iv_setting) ImageView iv_setting;
    @BindView(R.id.iv_loading2) ImageView mIvLoading2;
    @BindView(R.id.iv_placeholder) ImageView iv_placeholder;
    @BindView(R.id.iv_placeholder_rotate) ImageView iv_placeholder_rotate;
    @BindView(R.id.iv_finger) ImageView iv_finger;
    @BindView(R.id.ll_guide) LinearLayout ll_guide;
    @BindView(R.id.tv_know) TextView tv_know;
    @BindView(R.id.rl_guide_monitor) RelativeLayout rl_guide_monitor;
    @BindView(R.id.tv_uid) TextView tv_uid;
    @BindView(R.id.tv_connect_num) TextView tv_connect_num;
    @BindView(R.id.ll_land_return) LinearLayout ll_land_return;
    @BindView(R.id.iv_land_more) ImageView iv_land_more;
    @BindView(R.id.iv_landscape_record) public ImageView iv_landscape_record;
    @BindView(R.id.iv_land_snapshot) ImageView iv_land_snapshot;
    @BindView(R.id.iv_full_screen) ImageView iv_full_screen;
    protected MyCamera mMyCamera;
    public final static int RECORDING_STATUS_NONE = 0;
    public final static int RECORDING_STATUS_LOADING = 1;
    public final static int RECORDING_STATUS_ING = 2;
    public int mRecordingState = RECORDING_STATUS_NONE;
    private Timer timer;
    private TimerTask timerTask;
    public String recordFile;
    private int mCameraVideoQuality;
    public boolean isListening = false;//  当前APP是否在监听
    public boolean isTalking = false;  //  当前设备是否在对讲
    HiChipDefines.HI_P2P_S_DISPLAY display_param = null;
    protected int filpChecked;
    protected int mirrorChecked;
    private HiChipDefines.HI_P2P_S_AUDIO_ATTR audio_attr;

    private int maxInputValue = 100;
    private int maxOutputValue = 100;

    private boolean mIsHaveVirtual = false;//是否有虚拟键盘
    private int mDp_250 = 0;//横屏pup的宽度
    private boolean mIsSwitchResolution = false;
    private boolean mVoiceIsTran = false; // 当前声音是否是传输状态
    private int lightModel = 0;// 0 non ,1.HI_P2P_WHITE_LIGHT_GET_EXT ,2.HI_P2P_WHITE_LIGHT_GET 3.纯白光灯
    private HiChipDefines.HI_P2P_WHITE_LIGHT_INFO light_info;
    private HiChipDefines.HI_P2P_WHITE_LIGHT_INFO_EXT light_info_ext;
    private HiChipDefines.ABSOLUTE_LIGHT_TYPE abs_light;

    @BindView(R.id.viewPager) ViewPager viewPager;
    private VpAdapter mVpAdapter;
    @BindView(R.id.iv_first_tab) ImageView iv_first_tab;
    @BindView(R.id.iv_second_tab) ImageView iv_second_tab;
    private SecondTabFrament secondTabFrament;
    private FirstTabFragment firstTabFragment;
    private boolean mIsTXTJ = false;//是否是图像调节  用来区分 点击镜像翻转和图像调节发的命令
    private TextView tv_brightness;
    private TextView tv_contrast;
    private TextView tv_saturation;

    @BindView(R.id.rl_landscape_one) public RelativeLayout rl_landscape_one;//横屏的Top
    @BindView(R.id.rl_landscape_buttom) public RelativeLayout rl_landscape_buttom;//横屏的Buttom
    public boolean mIsHaveTrack = false;
    @BindView(R.id.iv_ydzz_land) public ImageView iv_ydzz_land;
    protected HiChipDefines.HI_P2P_SMART_MOTO trackParam;

    private List<Toast> toastList = new ArrayList<>();

    @Override
    protected int setLayoutId() {
        return R.layout.activity_live_view;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getIntentData();
        initViewAndData();
        startLiveShow();
        getLightModel();
        initViewPager();
        setListeners();
        getData();
    }

    private void startLiveShow() {
        if (mMyCamera != null) {
            new Thread() {
                public void run() {
                    mMyCamera.startLiveShow(mMyCamera.getVideoQuality(), mMonitor);
                }
            }.start();
            mMyCamera.registerPlayStateListener(this);
            mMyCamera.registerIOSessionListener(this);
        }
    }

    private void initViewPager() {
        firstTabFragment = new FirstTabFragment();
        firstTabFragment.setmMyCamera(mMyCamera);
        secondTabFrament = new SecondTabFrament();
        secondTabFrament.setmMyCamera(mMyCamera);
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(firstTabFragment);
        fragments.add(secondTabFrament);
        mVpAdapter = new VpAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(mVpAdapter);
        viewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                viewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                firstTabFragment.initHeight(viewPager.getHeight());
                secondTabFrament.initHeight(viewPager.getHeight());
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    iv_first_tab.setSelected(true);
                    iv_second_tab.setSelected(false);
                } else if (position == 1) {
                    iv_first_tab.setSelected(false);
                    iv_second_tab.setSelected(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void getData() {
        handIsSup_DEV_INFO_EXT();
    }

    private void handIsSup_DEV_INFO_EXT() {
        if (mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_DEV_INFO_EXT)) {
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_DEV_INFO_EXT, new byte[0]);
        } else {
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_DEV_INFO, new byte[0]);
        }
    }

    private void getLightModel() {
        boolean b = mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_ABSOLUTE_LIGHT_TYPE);
        if (b) {
            lightModel = 3;
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_ABSOLUTE_LIGHT_TYPE, null);
            return;
        }
        b = mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_WHITE_LIGHT_GET_EXT);
        if (b) {
            lightModel = 1;
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_WHITE_LIGHT_GET_EXT, null);
            return;
        }
        b = mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_WHITE_LIGHT_GET);
        if (b) {
            lightModel = 2;
            mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_WHITE_LIGHT_GET, null);
        }
        //智能追踪
        mIsHaveTrack = mMyCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_SMART_MOTO);
        iv_ydzz_land.setVisibility(mIsHaveTrack ? View.VISIBLE : View.GONE);
    }

    private void setListeners() {
        mMonitor.setOnTouchListener(this);
        tv_video_quality.setOnClickListener(this);
        iv_landscape_listen.setOnClickListener(this);
        iv_landscape_talk.setOnClickListener(this);
        tv_landscape_video_quality.setOnClickListener(this);
        btn_return.setOnClickListener(this);
        iv_setting.setOnClickListener(this);
        tv_know.setOnClickListener(this);
        rl_guide_monitor.setOnTouchListener(this);
        ll_land_return.setOnClickListener(this);
        iv_land_more.setOnClickListener(this);
        iv_landscape_record.setOnClickListener(this);
        iv_land_snapshot.setOnClickListener(this);
        iv_full_screen.setOnClickListener(this);
        iv_ydzz_land.setOnClickListener(this);
    }

    //获取相应的Camera,并做安全判断
    private void getIntentData() {
        String uid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        for (MyCamera camera : HiDataValue.CameraList) {
            if (!TextUtils.isEmpty(camera.getUid())) {
                if (camera.getUid().equalsIgnoreCase(uid)) {
                    this.mMyCamera = camera;
                    break;
                }
            }
        }
        mCameraVideoQuality = mMyCamera.getVideoQuality();
    }

    private float dis_hor;

    private void initViewAndData() {
        mDp_250 = HiTools.dip2px(this, 250);
        mMonitor.setCamera(mMyCamera);
        showPlaceLoadingView();
        if (mMyCamera.snapshot != null) {
            iv_placeholder.setImageBitmap(mMyCamera.snapshot);
            mMonitor.setVisibility(View.GONE);
        } else {
            iv_placeholder.setImageResource(R.mipmap.videoclip);
        }
        title_middle.setText(mMyCamera.getNikeName());
        mMyCamera.setLiveShowMonitor(mMonitor);
        tv_video_quality.setText(mCameraVideoQuality == 0 ? getString(R.string.high_definition) : getString(R.string.fluent));
        ll_guide.setVisibility(mMyCamera.isFirstEnterLive ? View.VISIBLE : View.GONE);
        if (mMyCamera.isFirstEnterLive) {
            handAnim();
        }

        tv_uid.setText(mMyCamera.getUid());

        mIsHaveVirtual = HiTools.checkDeviceHasNavigationBar(this);
        if (mIsHaveVirtual) {//做适配
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, mDp_250);
            mMonitor.setLayoutParams(params);
            iv_placeholder.setLayoutParams(params);
            RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            param.setMargins(10, HiTools.dip2px(this, 215), 10, 3);
            rl_wrap.setLayoutParams(param);
        }
        iv_first_tab.setSelected(true);
    }

    private float dis_ver;

    /**
     * 第一次进入界面的指导动画效果
     */
    private void handAnim() {
        dis_hor = HiTools.dip2px(this, 140);
        dis_ver = HiTools.dip2px(this, 80);
        ObjectAnimator anim = ObjectAnimator.ofFloat(iv_finger, "translationX", 0f, dis_hor, 0f);//向右
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        anim.setDuration(2000);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                ObjectAnimator anim_1 = ObjectAnimator.ofFloat(iv_finger, "rotation", 0f, 90f);//右转下
                anim_1.setInterpolator(new AccelerateDecelerateInterpolator());
                anim_1.setDuration(1000);
                anim_1.start();
                anim_1.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        ObjectAnimator anim_2 = ObjectAnimator.ofFloat(iv_finger, "translationY", 0f, dis_ver, 0f);//向下
                        anim_2.setInterpolator(new AccelerateDecelerateInterpolator());
                        anim_2.setDuration(2000);
                        anim_2.start();
                        anim_2.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                ObjectAnimator anim_3 = ObjectAnimator.ofFloat(iv_finger, "rotation", 90f, 180f);//下转左
                                anim_3.setInterpolator(new AccelerateDecelerateInterpolator());
                                anim_3.setDuration(1000);
                                anim_3.start();
                                anim_3.addListener(new AnimatorListenerAdapter() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        ObjectAnimator anim_4 = ObjectAnimator.ofFloat(iv_finger, "translationX", 0f, -dis_hor, 0f);//向左
                                        anim_4.setInterpolator(new AccelerateDecelerateInterpolator());
                                        anim_4.setDuration(2000);
                                        anim_4.start();
                                        anim_4.addListener(new AnimatorListenerAdapter() {
                                            @Override
                                            public void onAnimationEnd(Animator animation) {
                                                ObjectAnimator anim_5 = ObjectAnimator.ofFloat(iv_finger, "rotation", 180f, 270f);//左转上
                                                anim_5.setInterpolator(new AccelerateDecelerateInterpolator());
                                                anim_5.setDuration(1000);
                                                anim_5.start();
                                                anim_5.addListener(new AnimatorListenerAdapter() {
                                                    @Override
                                                    public void onAnimationEnd(Animator animation) {
                                                        ObjectAnimator anim_6 = ObjectAnimator.ofFloat(iv_finger, "translationY", 0f, -dis_ver, 0f);//向上
                                                        anim_6.setInterpolator(new AccelerateDecelerateInterpolator());
                                                        anim_6.setDuration(2000);
                                                        anim_6.start();
                                                        anim_6.addListener(new AnimatorListenerAdapter() {
                                                            @Override
                                                            public void onAnimationEnd(Animator animation) {
                                                                ObjectAnimator anim_7 = ObjectAnimator.ofFloat(iv_finger, "rotation", 270f, 360f);//上转右
                                                                anim_7.setInterpolator(new AccelerateDecelerateInterpolator());
                                                                anim_7.setDuration(1000);
                                                                anim_7.start();
                                                                anim_7.addListener(new AnimatorListenerAdapter() {
                                                                    @Override
                                                                    public void onAnimationEnd(Animator animation) {
                                                                        mAnimHandler.sendEmptyMessage(0X850);
                                                                    }
                                                                });
                                                            }
                                                        });
                                                    }
                                                });
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    }

    private Handler mAnimHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0X850:
                    handAnim();
                    break;
            }
        }
    };

    private void cancelToast(List<Toast> list) {
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) != null) {
                    list.get(i).cancel();
                }
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        cancelToast(toastList);
        mVoiceIsTran = false;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }

        if (mMyCamera != null) {
            mMyCamera.stopLiveShow();
            mMyCamera.unregisterPlayStateListener(this);
            mMyCamera.unregisterIOSessionListener(this);
        }
        if (mAnimHandler != null) {
            mAnimHandler.removeCallbacksAndMessages(null);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mRecHandler != null) {
            mRecHandler.removeCallbacksAndMessages(null);
        }
        if (mRecordingState == RECORDING_STATUS_ING) {
            grabRecordSnapshot();
        }
        Log.i("tedu","--onPause 2222--");
        finish();
    }

    @Override
    public void onBackPressed() {
        if (mMonitor.getmIsFullScreen() == 0) {
            iv_placeholder.setImageBitmap(mMyCamera.getSnapshot_EXT(1, 640, 352));
            iv_placeholder.animate().alpha(0.5f).setDuration(0).start();
            mMonitor.setVisibility(View.GONE);//解决共享元素 后mMonitor会闪一下
            if (secondTabFrament != null && secondTabFrament.mPopupWindow != null && secondTabFrament.mPopupWindow.isShowing()) {
                secondTabFrament.mPopupWindow.dismiss();
            }
            super.onBackPressed();
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    private void grabRecordSnapshot() {
        Bitmap frame = mMyCamera != null ? mMyCamera.getSnapshot_EXT(1, 640, 352) : null;
        if (frame != null) {
            saveRecordSnapshot(frame);
        }
    }

    @Override
    public void receiveSessionState(HiCamera arg0, int arg1) {
        if (mMyCamera != arg0) return;
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_SESSION_STATE;
        msg.arg1 = arg1;
        msg.obj = arg0;
        mHandler.sendMessage(msg);

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }


    @Override
    public void callbackState(HiCamera camera, int arg1, int arg2, int arg3) {
        if (mMyCamera != camera) return;
        Bundle bundle = new Bundle();
        bundle.putInt("command", arg1);
        bundle.putInt("width", arg2);
        bundle.putInt("height", arg3);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_PLAY_STATE;
        msg.setData(bundle);
        mHandler.sendMessage(msg);

    }

    @Override
    public void callbackPlayUTC(HiCamera hiCamera, int i) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.live_monitor:
                return handOnTouchMonitor(event);
            case R.id.rl_guide_monitor://指导页面 滑动了
                handGuideMonitor(event);
                return true;
        }

        return false;
    }

    private void handGuideMonitor(MotionEvent event) {
        int nCnt = event.getPointerCount();
        if (nCnt == 1) {//一个手指
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    down_X = event.getRawX();
                    down_Y = event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    handCloudStep(event);
                    ll_guide.setVisibility(View.GONE);
                    SharePreUtils.putBoolean(HiDataValue.CACHE, this, mMyCamera.getUid() + "isFirstEnterLive", false);
                    break;
            }


        }
    }

    private void handCloudStep(MotionEvent event) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screen_width = metrics.widthPixels;
        if (mMonitor.getState() == 0) {//正常 没有放大
            float disX = event.getRawX() - down_X;
            float disY = event.getRawY() - down_Y;
            float abs_disX = Math.abs(disX);
            float abs_disY = Math.abs(disY);
            int rateX = (int) Math.ceil((abs_disX / (screen_width / 2)) * 100);
            int rateY = (int) Math.ceil((abs_disY / (screen_width / 2)) * 100);
            rateX = rateX > 100 ? 100 : rateX;
            rateY = rateY > 100 ? 100 : rateY;
            //speed 这个要写死   speed是速度
            short speed = (short) (mMyCamera.getChipVersion() == HiDeviceInfo.CHIP_VERSION_GOKE ? 25 : 50);
            if (mMyCamera.getChipVersion() != HiDeviceInfo.CHIP_VERSION_GOKE) {
                rateX = rateX * 2;
                rateY = rateY * 2;
            }
            if (disX > 0 && abs_disX > FLING_MIN_DISTANCE) {//向右滑动
                int channel = HiChipP2P.HI_P2P_SE_CMD_CHN;
                int ctrl = HiChipDefines.HI_P2P_PTZ_CTRL_LEFT;
                int mode = HiChipDefines.HI_P2P_PTZ_MODE_STEP;
                short turntime = (short) rateX;//转动持续时间 1-100  0的话 无
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(channel, ctrl, mode, speed, turntime));
            } else if (disX < 0 && abs_disX > FLING_MIN_DISTANCE) {//向左滑动
                int channel = HiChipP2P.HI_P2P_SE_CMD_CHN;
                int ctrl = HiChipDefines.HI_P2P_PTZ_CTRL_RIGHT;
                int mode = HiChipDefines.HI_P2P_PTZ_MODE_STEP;
                short turntime = (short) rateX;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(channel, ctrl, mode, speed, turntime));
            }
            if (disY > 0 && abs_disY > FLING_MIN_DISTANCE) {//向上滑动
                int channel = HiChipP2P.HI_P2P_SE_CMD_CHN;
                int ctrl = HiChipDefines.HI_P2P_PTZ_CTRL_UP;
                int mode = HiChipDefines.HI_P2P_PTZ_MODE_STEP;
                short turntime = (short) rateY;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(channel, ctrl, mode, speed, turntime));

            } else if (disY < 0 && abs_disY > FLING_MIN_DISTANCE) {//向下滑动
                int channel = HiChipP2P.HI_P2P_SE_CMD_CHN;
                int ctrl = HiChipDefines.HI_P2P_PTZ_CTRL_DOWN;
                int mode = HiChipDefines.HI_P2P_PTZ_MODE_STEP;
                short turntime = (short) rateY;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(channel, ctrl, mode, speed, turntime));
            }
        }
    }


    int xlenOld;
    int ylenOld;
    double nLenStart = 0;
    private static final int FLING_MIN_DISTANCE = 60;

    //处理monitor的onTouch 捏合放大缩小
    private boolean handOnTouchMonitor(MotionEvent event) {
        int nCnt = event.getPointerCount();
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN && 2 == nCnt) {
            for (int i = 0; i < nCnt; i++) {
                float x = event.getX(i);
                float y = event.getY(i);
            }
            xlenOld = Math.abs((int) event.getX(0) - (int) event.getX(1));
            ylenOld = Math.abs((int) event.getY(0) - (int) event.getY(1));
            nLenStart = Math.sqrt((double) xlenOld * xlenOld + (double) ylenOld * ylenOld);
        } else if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE && 2 == nCnt) {
            for (int i = 0; i < nCnt; i++) {
                float x = event.getX(i);
                float y = event.getY(i);
            }
            int xlen = Math.abs((int) event.getX(0) - (int) event.getX(1));
            int ylen = Math.abs((int) event.getY(0) - (int) event.getY(1));
            int moveX = Math.abs(xlen - xlenOld);
            int moveY = Math.abs(ylen - ylenOld);
            double nLenEnd = Math.sqrt((double) xlen * xlen + (double) ylen * ylen);
            if (moveX < 20 && moveY < 20) {
                return false;
            }
            if (nLenEnd > nLenStart) {
                resetMonitorSize(true, nLenEnd);
            } else {
                resetMonitorSize(false, nLenEnd);
            }
            xlenOld = xlen;
            ylenOld = ylen;
            nLenStart = nLenEnd;
            return true;
        } else if (nCnt == 1) {//一个手指
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    down_X = event.getRawX();
                    down_Y = event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    float up_x=event.getRawX();
                    float up_y=event.getRawY();
                    float dis_x=up_x-down_X;
                    float dis_y=up_y-down_Y;
                    if(dis_x>0&&Math.abs(dis_x)>Math.abs(dis_y)){//右滑
                        int rote= (int) (((float)Math.abs(dis_x)/(mMonitor.screen_width/2))*100);
                        if(rote>100) rote=100;
                        if(rote<=0) rote=1;
                        Log.i("tedu","--右滑----dis_x:"+dis_x+"--mMonitor.width--:"+mMonitor.screen_width+"--rote--:"+rote);
                        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL,
                                HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_RIGHT, HiChipDefines.HI_P2P_PTZ_MODE_STEP, (short)50, (short) rote));
                    }
                    if(dis_x<0&&Math.abs(dis_x)>Math.abs(dis_y)){//左滑
                        int rote= (int) (((float)Math.abs(dis_x)/(mMonitor.screen_width/2))*100);
                        if(rote>100) rote=100;
                        if(rote<=0) rote=1;
                        Log.i("tedu","--左滑----dis_x:"+dis_x+"--mMonitor.width--:"+mMonitor.screen_width+"--rote--:"+rote);
                        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL,
                                HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_LEFT, HiChipDefines.HI_P2P_PTZ_MODE_STEP, (short)50, (short) rote));
                    }
                    if(dis_y>0&&Math.abs(dis_y)>Math.abs(dis_x)){
                        int rote= (int) (((float)Math.abs(dis_y)/(mMonitor.screen_width/2))*100);
                        if(rote>100) rote=100;
                        if(rote<=0) rote=1;
                        Log.i("tedu","--下滑----dis_x:"+dis_x+"--mMonitor.width--:"+mMonitor.screen_width+"--rote--:"+rote);
                        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL,
                                HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_DOWN, HiChipDefines.HI_P2P_PTZ_MODE_STEP, (short)50, (short) rote));
                    }
                    if(dis_y<0&&Math.abs(dis_y)>Math.abs(dis_x)){
                        int rote= (int) (((float)Math.abs(dis_y)/(mMonitor.screen_width/2))*100);
                        if(rote>100) rote=100;
                        if(rote<=0) rote=1;
                        Log.i("tedu","--上滑----dis_x:"+dis_x+"--mMonitor.width--:"+mMonitor.screen_width+"--rote--:"+rote);
                        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL,
                                HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_UP, HiChipDefines.HI_P2P_PTZ_MODE_STEP, (short)50, (short) rote));
                    }
                    //handCloudStep(event);
                    break;
            }
        }
        return false;
    }

    private float down_X;
    private float down_Y;

    int moveX;
    int moveY;

    private void resetMonitorSize(boolean large, double move) {
        if (mMonitor.getmIsFullScreen() == 0) {//竖屏
            mMonitor.screen_height = mDp_250;
        }
        if (mMonitor.height == 0 && mMonitor.width == 0) {
            initMatrix(mMonitor.screen_width, mMonitor.screen_height);
        }
        moveX = (int) (move / 2);
        moveY = (int) ((move * mMonitor.screen_height / mMonitor.screen_width) / 2);
        if (large) {
            if (mMonitor.width <= 2 * mMonitor.screen_width && mMonitor.height <= 2 * mMonitor.screen_height) {
                mMonitor.left -= (moveX / 2);
                mMonitor.bottom -= (moveY / 2);
                mMonitor.width += (moveX);
                mMonitor.height += (moveY);
            }
        } else {
            mMonitor.left += (moveX / 2);
            mMonitor.bottom += (moveY / 2);
            mMonitor.width -= (moveX);
            mMonitor.height -= (moveY);
        }
        if (mMonitor.left > 0 || mMonitor.width < mMonitor.screen_width || mMonitor.height < mMonitor.screen_height || mMonitor.bottom > 0) {
            initMatrix(mMonitor.screen_width, mMonitor.screen_height);
        }
        if (mMonitor.width > mMonitor.screen_width) {
            mMonitor.setState(1);
        } else {
            mMonitor.setState(0);
        }
        mMonitor.setMatrix(mMonitor.left, mMonitor.bottom, mMonitor.width, mMonitor.height);
    }

    private void initMatrix(int screen_width, int screen_height) {
        mMonitor.left = 0;
        mMonitor.bottom = 0;
        mMonitor.width = screen_width;
        mMonitor.height = screen_height;
    }

    public long mStartRecoedTime = 0;
    private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");

    public Handler mRecHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 110:
                    if (iv_recording.getVisibility() == View.INVISIBLE) {
                        iv_recording.setVisibility(View.VISIBLE);
                    } else {
                        iv_recording.setVisibility(View.INVISIBLE);
                    }
                    mStartRecoedTime += 1000;
                    tv_record_time.setText(sdf.format(new Date(mStartRecoedTime)));

                    mRecHandler.sendEmptyMessageDelayed(110, 1000);
                    break;
            }
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 播放状态
                case HiDataValue.HANDLE_MESSAGE_PLAY_STATE:
                    handMsgPlayState(msg);
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    handMsgReceiveIoctrl(msg);
                    break;
                case HiDataValue.HANDLE_MESSAGE_SESSION_STATE:
                    handMsgSessionState(msg);
                    break;
                case 0X120:
                    HiToast.showToast(LiveViewActivity.this, getString(R.string.failed_recording));
                    break;
            }

        }
    };

    private void handMsgSessionState(Message msg) {
        switch (msg.arg1) {
            case HiCamera.CAMERA_CONNECTION_STATE_DISCONNECTED:
                Log.i("tedu", "-LiveViewActivity-我断线了---");
                if (!mIsSwitchResolution) {
                    HiToast.showToast(getApplicationContext(), "网络异常!");
                    Log.i("tedu","--网络异常 1111--");
                    finish();
                }
                setViewWhetherClick(false);
                showLoadingView();
                if (mMyCamera != null) {
                    mMyCamera.stopLiveShow();
                    if (isListening) {
                        isListening = false;
                    }
                }
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_LOGIN:
                Log.i("tedu", "-LiveViewActivity-登录成功了---");
                mIsSwitchResolution = false;
                progressbar.setVisibility(View.GONE);
                if (mCameraVideoQuality != mMyCamera.getVideoQuality()) {
                    mMyCamera.stopRecording();
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    if (timerTask != null) {
                        timerTask.cancel();
                        timerTask = null;
                    }
                    mCameraVideoQuality = mMyCamera.getVideoQuality();
                    tv_video_quality.setText(mCameraVideoQuality == 0 ? getString(R.string.high_definition) : getString(R.string.fluent));
                    tv_landscape_video_quality.setText(mCameraVideoQuality == 0 ? getString(R.string.high_definition) : getString(R.string.fluent));
                }
                new Thread() {
                    public void run() {
                        mMyCamera.startLiveShow(mMyCamera.getVideoQuality(), mMonitor);
                    }
                }.start();
                break;
        }
    }

    private void handMsgReceiveIoctrl(Message msg) {
        if (msg.arg2 == 0) {// 0表示成功
            byte[] data = msg.getData().getByteArray(HiDataValue.EXTRAS_KEY_DATA);
            switch (msg.arg1) {
                case HiChipDefines.HI_P2P_GET_SMART_MOTO:
                    trackParam = new HiChipDefines.HI_P2P_SMART_MOTO(data);
                    boolean isSelect = trackParam.bSmartTrack == 0 ? false : true;
                    iv_ydzz_land.setSelected(isSelect);
                    Log.i("tedu", "-111-LiveViewActivity--智能追踪是否打开--:" + isSelect);
                    break;
                case HiChipDefines.HI_P2P_SET_DISPLAY_PARAM:
                    dismissjuHuaDialog();
                    break;
                case HiChipDefines.HI_P2P_GET_DEV_INFO_EXT:
                    HiChipDefines.HI_P2P_GET_DEV_INFO_EXT deviceInfo = new HiChipDefines.HI_P2P_GET_DEV_INFO_EXT(data);
                    if (deviceInfo.sUserNum < 1) {
                        deviceInfo.sUserNum = 1;
                    }
                    tv_connect_num.setText(deviceInfo.sUserNum + "");
                    break;
                case HiChipDefines.HI_P2P_GET_DEV_INFO:
                    HiChipDefines.HI_P2P_S_DEV_INFO info = new HiChipDefines.HI_P2P_S_DEV_INFO(data);
                    if (info.sUserNum < 1) {
                        info.sUserNum = 1;
                    }
                    tv_connect_num.setText(info.sUserNum + "");
                    break;
                case HiChipDefines.HI_P2P_GET_DISPLAY_PARAM:
                    display_param = new HiChipDefines.HI_P2P_S_DISPLAY(data);
                    if (mMonitor.getmIsFullScreen() == 1) {//横屏
                        if (ll_pup_main != null && ll_pup_content != null) {
                            if (mIsTXTJ) {
                                View child = View.inflate(LiveViewActivity.this, R.layout.view_land_txtj, null);
                                handLandShowContent(child);
                                //亮度
                                SeekBar sb_brightness = child.findViewById(R.id.sb_brightness);
                                tv_brightness = child.findViewById(R.id.tv_brightness);
                                tv_brightness.setText(display_param.u32Brightness + "");
                                sb_brightness.setMax(100);
                                sb_brightness.setProgress(display_param.u32Brightness);
                                sb_brightness.setOnSeekBarChangeListener(this);

                                //对比度
                                SeekBar sb_contrast = child.findViewById(R.id.sb_contrast);
                                tv_contrast = child.findViewById(R.id.tv_contrast);
                                tv_contrast.setText(display_param.u32Contrast + "");
                                sb_contrast.setMax(100);
                                sb_contrast.setProgress(display_param.u32Contrast);
                                sb_contrast.setOnSeekBarChangeListener(this);

                                //饱和度
                                SeekBar sb_saturation = child.findViewById(R.id.sb_saturation);
                                tv_saturation = child.findViewById(R.id.tv_saturation);
                                tv_saturation.setText(display_param.u32Saturation + "");
                                sb_saturation.setMax(255);
                                sb_saturation.setProgress(display_param.u32Saturation);
                                sb_saturation.setOnSeekBarChangeListener(this);
                            } else {
                                View child = View.inflate(LiveViewActivity.this, R.layout.view_land_mirror_flip, null);
                                handLandShowContent(child);
                                handMirrorFlip(child);
                            }
                        }
                    } else {//竖屏

                    }
                    break;
                case HiChipDefines.HI_P2P_SET_PTZ_PRESET:
                    if (mFlagPreset == 1) {
                        HiToast.showToast(LiveViewActivity.this, getString(R.string.tips_preset_set_btn));
                    } else if (mFlagPreset == 2) {
                        // HiToast.showToast(LiveViewActivity.this, "调用成功啦");
                    }
                    break;
                case HiChipDefines.HI_P2P_GET_AUDIO_ATTR:
                    audio_attr = new HiChipDefines.HI_P2P_S_AUDIO_ATTR(data);
                    if (mMonitor.getmIsFullScreen() == 1) {//横屏
                        View child = View.inflate(LiveViewActivity.this, R.layout.view_land_volume, null);
                        handLandShowContent(child);
                        if (mMyCamera.getChipVersion() == HiDeviceInfo.CHIP_VERSION_GOKE) {
                            maxInputValue = 16;
                            maxOutputValue = 13;
                        }
                        seekbar_input = child.findViewById(R.id.seekbar_input);
                        TextView txt_input_value = child.findViewById(R.id.txt_input_value);
                        if (audio_attr != null) {
                            seekbar_input.setProgress(audio_attr.u32InVol - 1);
                            txt_input_value.setText(String.valueOf(audio_attr.u32InVol));
                        }
                        seekbar_input.setMax(maxInputValue - 1);
                        seekbar_input.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {
                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {
                                txt_input_value.setText(String.valueOf(seekBar.getProgress() + 1));
                                sendToDevice();
                            }
                        });
                        seekbar_output = child.findViewById(R.id.seekbar_output);
                        TextView txt_output_value = child.findViewById(R.id.txt_output_value);
                        if (audio_attr != null) {
                            seekbar_output.setProgress(audio_attr.u32OutVol - 1);
                            txt_output_value.setText(String.valueOf(audio_attr.u32OutVol));
                        }
                        seekbar_output.setMax(maxOutputValue - 1);
                        seekbar_output.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {
                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {
                                txt_output_value.setText(String.valueOf(seekBar.getProgress() + 1));
                                sendToDevice();
                            }
                        });
                    } else {//竖屏
                        View child = View.inflate(this, R.layout.view_volume, null);
                        //handVolume(child);
                    }
                    break;
                case HiChipDefines.HI_P2P_SET_AUDIO_ATTR:
                    dismissjuHuaDialog();
                    break;
                case HiChipDefines.HI_P2P_WHITE_LIGHT_GET:
                    if (lightModel != 2) {
                        return;
                    }
                    light_info = new HiChipDefines.HI_P2P_WHITE_LIGHT_INFO(data);
                    break;
                case HiChipDefines.HI_P2P_WHITE_LIGHT_GET_EXT:
                    if (lightModel != 1) {
                        return;
                    }
                    light_info_ext = new HiChipDefines.HI_P2P_WHITE_LIGHT_INFO_EXT(data);
                    break;
                case HiChipDefines.HI_P2P_GET_ABSOLUTE_LIGHT_TYPE:
                    if (lightModel != 3) return;
                    abs_light = new HiChipDefines.ABSOLUTE_LIGHT_TYPE(data);
                    break;
            }
        } else {
            switch (msg.arg1) {
                case HiChipDefines.HI_P2P_SET_PTZ_PRESET:
                    if (mFlagPreset == 1) {
                        HiToast.showToast(LiveViewActivity.this, getString(R.string.tip_preset_fail));
                    }
                    break;
                case HiChipDefines.HI_P2P_SET_DISPLAY_PARAM:
                    break;
            }
        }
    }

    //点击 横屏工具栏详情的view 处理
    private void handLandShowContent(View child) {
        ll_pup_main.setVisibility(View.GONE);
        ll_pup_content.setVisibility(View.VISIBLE);
        ll_pup_content.removeAllViews();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        ll_pup_content.addView(child, params);
        ObjectAnimator animator = ObjectAnimator.ofFloat(child, "translationX", mDp_250, 0);
        animator.setDuration(300);
        animator.start();
        //返回上一级
        LinearLayout ll_land_mirror_flip = child.findViewById(R.id.ll_land_mirror_flip);
        if (ll_land_mirror_flip != null) {
            ll_land_mirror_flip.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ObjectAnimator animator = ObjectAnimator.ofFloat(child, "translationX", 0, mDp_250);
                    animator.setDuration(300);
                    animator.start();
                    animator.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            ll_pup_content.setVisibility(View.GONE);
                            ll_pup_main.setVisibility(View.VISIBLE);
                            ObjectAnimator animator = ObjectAnimator.ofFloat(ll_pup_main, "Alpha", 0f, 1f);
                            animator.setDuration(200);
                            animator.start();
                        }
                    });
                }
            });
        }

    }

    //处理 镜像和翻转的SwitchButton 的业务逻辑(可以横竖屏通用)
    private void handMirrorFlip(View child) {
        if (display_param == null) return;
        //镜像
        SwitchButton switch_btn_mirror = child.findViewById(R.id.switch_btn_mirror);
        switch_btn_mirror.setChecked(display_param.u32Mirror == 1 ? true : false);
        switch_btn_mirror.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mirrorChecked = isChecked ? 1 : 0;
                display_param.u32Mirror = mirrorChecked;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_DISPLAY_PARAM, display_param.parseContent());
                showjuHuaDialog();
            }
        });

        //翻转
        SwitchButton switch_btn_flip = child.findViewById(R.id.switch_btn_flip);
        switch_btn_flip.setChecked(display_param.u32Flip == 1 ? true : false);
        switch_btn_flip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                filpChecked = isChecked ? 1 : 0;
                display_param.u32Flip = filpChecked;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_DISPLAY_PARAM, display_param.parseContent());
                showjuHuaDialog();
            }
        });
    }


    private void clickVolume(ImageView iv_landscape_volume) {
        if (audio_attr == null) return;
        View customView = View.inflate(this, R.layout.view_volume, null);
        mPopupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-0000);
        mPopupWindow.setBackgroundDrawable(cd);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setWidth(mDp_250);
        mPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);

        int[] location = new int[2];
        iv_landscape_volume.getLocationOnScreen(location);
        int offsetY = HiTools.dip2px(this, 130);
        int offsetX = HiTools.dip2px(this, 95);
        mPopupWindow.showAtLocation(iv_landscape_volume, 0, location[0] - offsetX, location[1] - offsetY);

        SeekBar seekbar_input = customView.findViewById(R.id.seekbar_input);
        SeekBar seekbar_output = customView.findViewById(R.id.seekbar_output);
        TextView txt_input_value = customView.findViewById(R.id.txt_input_value);
        TextView txt_output_value = customView.findViewById(R.id.txt_output_value);
        if (seekbar_input == null) return;
        seekbar_input.setProgress(audio_attr.u32InVol - 1);
        txt_input_value.setText(String.valueOf(audio_attr.u32InVol));
        seekbar_output.setProgress(audio_attr.u32OutVol - 1);
        txt_output_value.setText(String.valueOf(audio_attr.u32OutVol));
        if (mMyCamera.getChipVersion() == HiDeviceInfo.CHIP_VERSION_GOKE) {
            maxInputValue = 16;
            maxOutputValue = 13;
        }
        seekbar_input.setMax(maxInputValue - 1);
        seekbar_input.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                txt_input_value.setText(String.valueOf(seekBar.getProgress() + 1));
                sendToDevice(seekbar_input, seekbar_output);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }
        });

        seekbar_output.setMax(maxOutputValue - 1);
        seekbar_output.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                txt_output_value.setText(String.valueOf(seekBar.getProgress() + 1));
                sendToDevice(seekbar_input, seekbar_output);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }
        });
    }


    private void sendToDevice(SeekBar seekbar_input, SeekBar seekbar_output) {
        if (audio_attr == null) return;
        int invol = seekbar_input.getProgress() + 1;
        int outvol = seekbar_output.getProgress() + 1;
        showjuHuaDialog();
        //默认线性输入
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_AUDIO_ATTR, HiChipDefines.HI_P2P_S_AUDIO_ATTR.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, audio_attr.u32Enable, audio_attr.u32Stream, audio_attr.u32AudioType, 0, invol, outvol));
    }

    private void handMsgPlayState(Message msg) {
        Bundle bundle = msg.getData();
        int command = bundle.getInt("command");
        switch (command) {
            // 接收到了开始的状态
            case ICameraPlayStateCallback.PLAY_STATE_START:
                Log.i("tedu", "-LiveViewActivity-开始播放了---");
                setViewWhetherClick(true);
                dismissPlaceLoadingView();
                dismissjuHuaDialog();
                dismissLoadingView();
                mMonitor.setVisibility(View.VISIBLE);
                Bitmap frame = mMyCamera != null ? mMyCamera.getSnapshot_EXT(1, 640, 352) : null;
                if (frame != null) {
                    HiTools.saveSnapshot(frame, mMyCamera, LiveViewActivity.this);
                }
                break;
        }
    }

    private void saveRecordSnapshot(final Bitmap frame) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... arg0) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    String path = HiDataValue.getPathCameraLocalRecordSnapShot(mMyCamera.getUid(),LiveViewActivity.this);
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    if (!TextUtils.isEmpty(recordFile)) {
                        File f = new File(recordFile);
                        if (f != null && f.exists()) {
                            HiTools.saveBitmap(frame, file.getAbsolutePath() + "/" + f.getName());
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
            }
        }.execute();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_setting:
                Intent intent = new Intent(LiveViewActivity.this, SettingActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
                startActivity(intent);
                break;
            case R.id.btn_return:
                if (secondTabFrament != null && secondTabFrament.mPopupWindow != null && secondTabFrament.mPopupWindow.isShowing()) {
                    secondTabFrament.mPopupWindow.dismiss();
                }
                iv_placeholder.setImageBitmap(mMyCamera.getSnapshot_EXT(1, 640, 352));
                iv_placeholder.animate().alpha(1f).setDuration(0).start();
                mMonitor.setVisibility(View.GONE);//解决共享元素 后mMonitor会闪一下
                super.onBackPressed();
                break;
            case R.id.tv_video_quality://竖屏  点击切换画质
                handVideoQuality(tv_video_quality, HiTools.dip2px(this, 15));
                break;
            case R.id.iv_full_screen://全屏
                if (secondTabFrament != null && secondTabFrament.mPopupWindow != null && secondTabFrament.mPopupWindow.isShowing()) {
                    secondTabFrament.mPopupWindow.dismiss();
                }
                mMonitor.setVisibility(View.INVISIBLE);//解决魅族 5 横屏无视频
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                break;
            case R.id.tv_landscape_video_quality://横屏 切换画质
                handVideoQuality(tv_landscape_video_quality, HiTools.dip2px(this, 20));
                break;
            case R.id.tv_know://知道了
                if (mHandler != null) {
                    mHandler.removeCallbacksAndMessages(null);
                }
                ll_guide.setVisibility(View.GONE);
                SharePreUtils.putBoolean(HiDataValue.CACHE, this, mMyCamera.getUid() + "isFirstEnterLive", false);
                break;
            case R.id.ll_land_return:// 横屏的 返回
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                break;
            case R.id.iv_land_more://横屏的 更多工具栏
                handLandMore();
                break;
            case R.id.iv_landscape_record://横屏的  录制
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
                    showAlertDialog();
                    return;
                }
                clickRecording();
                break;
            case R.id.iv_landscape_listen://横屏的  监听
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(this, Manifest.permission.RECORD_AUDIO) || !HiTools.checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
                    showAlertDialog();
                    return;
                }
                clickListen();
                break;
            case R.id.iv_landscape_talk://横屏的  对讲
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(this, Manifest.permission.RECORD_AUDIO) || !HiTools.checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
                    showAlertDialog();
                    return;
                }
                handTalking();
                break;
            case R.id.iv_land_snapshot://横屏的  截图
                if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(this, Manifest.permission.RECORD_AUDIO) || !HiTools.checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
                    showAlertDialog();
                    return;
                }
                handSnapshot();
                break;
            case R.id.iv_ydzz_land://横屏的 移动追踪
                int isChecked = 0;
                if (iv_ydzz_land.isSelected()) {
                    isChecked = 0;
                    iv_ydzz_land.setSelected(false);
                    HiToast.showToast(this, "移动追踪已关闭");
                    if (secondTabFrament.lightModel == 0) {
                        secondTabFrament.ll_added_item_one.setSelected(false);
                    } else if (secondTabFrament.lightModel != 0 && secondTabFrament.mIsHaveTrack) {
                        secondTabFrament.ll_added_item_one.setSelected(false);
                    }
                } else {
                    isChecked = 1;
                    iv_ydzz_land.setSelected(true);
                    HiToast.showToast(this, "移动追踪已开启");
                    if (secondTabFrament.lightModel == 0) {
                        secondTabFrament.ll_added_item_one.setSelected(true);
                    } else if (secondTabFrament.lightModel != 0 && secondTabFrament.mIsHaveTrack) {
                        secondTabFrament.ll_added_item_one.setSelected(true);
                    }
                }
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_SMART_MOTO, trackParam.parseContent(isChecked));
                break;
        }
    }

    private void handWork(View child) {
        RadioButton[] lightRadioBtnsRES = new RadioButton[3];
        RadioButton[] lightRadioBtnsNOR = new RadioButton[2];

        RadioGroup live_view_ext_layout = (RadioGroup) child.findViewById(R.id.live_view_ext_layout);
        RadioGroup live_view_nor_layout = (RadioGroup) child.findViewById(R.id.live_view_nor_layout);
        RadioGroup live_view_abs_light_layout = (RadioGroup) child.findViewById(R.id.live_view_abs_light_layout);
        lightRadioBtnsRES[0] = (RadioButton) child.findViewById(R.id.live_view_ext_btn_normal);
        lightRadioBtnsRES[1] = (RadioButton) child.findViewById(R.id.live_view_ext_btn_color);
        lightRadioBtnsRES[2] = (RadioButton) child.findViewById(R.id.live_view_ext_btn_auto);
        lightRadioBtnsNOR[0] = (RadioButton) child.findViewById(R.id.live_view_nor_btn_open);
        lightRadioBtnsNOR[1] = (RadioButton) child.findViewById(R.id.live_view_nor_btn_close);

        if (lightModel == 2) {
            live_view_ext_layout.setVisibility(View.GONE);
            live_view_abs_light_layout.setVisibility(View.GONE);
            live_view_nor_layout.setVisibility(View.VISIBLE);
            if (light_info != null && light_info.u32State < 2) {
                lightRadioBtnsNOR[light_info.u32State].setChecked(true);
            }
        } else if (lightModel == 1) {
            live_view_ext_layout.setVisibility(View.VISIBLE);
            live_view_nor_layout.setVisibility(View.GONE);
            live_view_abs_light_layout.setVisibility(View.GONE);
            if (light_info_ext != null && light_info_ext.u32State < 3) {
                lightRadioBtnsRES[light_info_ext.u32State].setChecked(true);
            }
        } else if (lightModel == 3) {
            live_view_abs_light_layout.setVisibility(View.VISIBLE);
            live_view_ext_layout.setVisibility(View.GONE);
            live_view_nor_layout.setVisibility(View.GONE);
            if (abs_light != null && abs_light.s32State < 3) {
                RadioButton rBtn = (RadioButton) live_view_abs_light_layout.getChildAt(abs_light.s32State);
                rBtn.setChecked(true);
            }
        }
        live_view_ext_layout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup rg, int id) {
                if (light_info_ext == null) return;
                switch (id) {
                    case R.id.live_view_ext_btn_normal:
                        light_info_ext.u32State = 0;
                        break;
                    case R.id.live_view_ext_btn_color:
                        light_info_ext.u32State = 1;
                        break;
                    case R.id.live_view_ext_btn_auto:
                        light_info_ext.u32State = 2;
                        break;
                }
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_WHITE_LIGHT_SET_EXT, HiChipDefines.HI_P2P_WHITE_LIGHT_INFO_EXT.parseContent(light_info_ext.u32Chn, light_info_ext.u32State));
            }
        });

        live_view_nor_layout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup rg, int id) {
                if (light_info == null) return;
                switch (id) {
                    case R.id.live_view_nor_btn_open:
                        light_info.u32State = 0;
                        break;
                    case R.id.live_view_nor_btn_close:
                        light_info.u32State = 1;
                        break;
                }
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_WHITE_LIGHT_SET, HiChipDefines.HI_P2P_WHITE_LIGHT_INFO.parseContent(light_info.u32Chn, light_info.u32State));

            }
        });

        live_view_abs_light_layout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (abs_light == null) return;
                switch (checkedId) {
                    case R.id.abs_light_auto:
                        abs_light.s32State = 0;
                        break;
                    case R.id.abs_light_open:
                        abs_light.s32State = 1;
                        break;
                    case R.id.abs_light_close:
                        abs_light.s32State = 2;
                        break;
                }
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_ABSOLUTE_LIGHT_TYPE, HiChipDefines.ABSOLUTE_LIGHT_TYPE.parseContent(abs_light.s32State));
            }
        });
    }

    private PopupWindow mPopupWindow;
    private LinearLayout ll_pup_content;
    private LinearLayout ll_pup_main;

    private void handLandMore() {
        View custom = View.inflate(LiveViewActivity.this, R.layout.pup_landscape_more, null);
        mPopupWindow = new PopupWindow(custom);
        ColorDrawable cd = new ColorDrawable(-000);
        mPopupWindow.setBackgroundDrawable(cd);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        mPopupWindow.setWidth(mDp_250);
        mPopupWindow.setAnimationStyle(R.style.AnimTopRight);
        mPopupWindow.showAtLocation(custom, Gravity.CENTER, getWindowManager().getDefaultDisplay().getWidth(), 0);
        AnimationProUtils.alpha1To0(rl_landscape_view, 300);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                AnimationProUtils.alpha0To1(rl_landscape_view, 300);
            }
        });

        ll_pup_content = custom.findViewById(R.id.ll_pup_content);
        ll_pup_main = custom.findViewById(R.id.ll_pup_main);

        //横屏  镜像/翻转
        ImageView land_iv_mirror_flip = custom.findViewById(R.id.land_iv_mirror_flip);
        land_iv_mirror_flip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsTXTJ = false;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_DISPLAY_PARAM, null);
            }
        });

        //横屏 聚焦加减
        ImageView land_iv_focusing = custom.findViewById(R.id.land_iv_focusing);
        land_iv_focusing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View child = View.inflate(LiveViewActivity.this, R.layout.view_land_zoom_focus, null);
                handLandShowContent(child);
                handZoomAndFocus(child);

            }
        });

        //横屏 预置位
        ImageView land_iv_preset = custom.findViewById(R.id.land_iv_preset);
        land_iv_preset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View child = View.inflate(LiveViewActivity.this, R.layout.view_land_preset, null);
                handLandShowContent(child);
                LiveViewModel.getInstance().handKeyBoard(LiveViewActivity.this, child, mMyCamera);
            }
        });

        //横屏 音量控制
        ImageView land_iv_volume = custom.findViewById(R.id.land_iv_volume);
        land_iv_volume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_AUDIO_ATTR, null);
            }
        });

        //横屏的图像调节
        ImageView iv_txtj_land = custom.findViewById(R.id.iv_txtj_land);
        iv_txtj_land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsTXTJ = true;
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_DISPLAY_PARAM, null);
            }
        });

        //横屏 夜视模式
        ImageView iv_night_mode_land = custom.findViewById(R.id.iv_night_mode_land);
        LinearLayout ll_night_mode_land = custom.findViewById(R.id.ll_night_mode_land);
        ll_night_mode_land.setVisibility(lightModel == 0 ? View.GONE : View.VISIBLE);
        iv_night_mode_land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View child = View.inflate(LiveViewActivity.this, R.layout.view_land_night_model, null);
                handLandShowContent(child);
                handWork(child);
            }
        });
    }


    //处理 拉近 拉远 聚焦加减的操作(横竖屏 通用)
    private void handZoomAndFocus(View child) {
        if (child == null) return;
        //拉近操作
        TextView tv_zoomin = child.findViewById(R.id.tv_zoomin);
        tv_zoomin.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_ZOOMIN, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_STOP, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                }
                return false;
            }
        });

        // 拉远按钮
        TextView tv_zoomout = child.findViewById(R.id.tv_zoomout);
        tv_zoomout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_ZOOMOUT, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_STOP, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                }
                return false;
            }
        });

        // 聚焦+
        TextView tv_focusin = child.findViewById(R.id.tv_focusin);
        tv_focusin.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_FOCUSIN, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_STOP, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                }
                return false;
            }
        });

        // 聚焦-
        TextView tv_focusout = child.findViewById(R.id.tv_focusout);
        tv_focusout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_FOCUSOUT, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_PTZ_CTRL, HiChipDefines.HI_P2P_S_PTZ_CTRL.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, HiChipDefines.HI_P2P_PTZ_CTRL_STOP, HiChipDefines.HI_P2P_PTZ_MODE_RUN, (short) MyLiveViewGLMonitor.PTZ_STEP, (short) 10));
                }
                return false;
            }
        });
    }

    private SeekBar seekbar_input, seekbar_output;


    private void sendToDevice() {
        if (audio_attr == null) {
            return;
        }
        int invol = seekbar_input.getProgress() + 1;
        int outvol = seekbar_output.getProgress() + 1;
        showjuHuaDialog();
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_AUDIO_ATTR, HiChipDefines.HI_P2P_S_AUDIO_ATTR.parseContent(HiChipP2P.HI_P2P_SE_CMD_CHN, audio_attr.u32Enable, audio_attr.u32Stream, audio_attr.u32AudioType, 0, invol, outvol));
    }

    public int mFlagPreset = 0; //1 标示设置   2标示调用

    private void FitVirtualKeyView() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, HiTools.dip2px(LiveViewActivity.this, 210));
        rl_preset_key.setLayoutParams(params);

        params = new LinearLayout.LayoutParams(HiTools.dip2px(LiveViewActivity.this, 135), LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);
        params.gravity = Gravity.CENTER_HORIZONTAL;
        tv_key_preset.setLayoutParams(params);

        params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, HiTools.dip2px(LiveViewActivity.this, 30));
        params.setMargins(HiTools.dip2px(LiveViewActivity.this, 10), HiTools.dip2px(LiveViewActivity.this, 10), HiTools.dip2px(LiveViewActivity.this, 10), 0);
        ll_key_one.setLayoutParams(params);
        ll_key_two.setLayoutParams(params);
        ll_key_there.setLayoutParams(params);
    }

    @BindView(R.id.rl_preset_key) RelativeLayout rl_preset_key;
    @BindView(R.id.tv_key_preset) TextView tv_key_preset;
    @BindView(R.id.ll_key_one) LinearLayout ll_key_one;
    @BindView(R.id.ll_key_two) LinearLayout ll_key_two;
    @BindView(R.id.ll_key_there) LinearLayout ll_key_there;


    private void handSnapshot() {
        clickSnapshot();
    }

    public void clickSnapshot() {
        if (mMyCamera != null) {
            if (HiTools.isSDCardValid()) {
                File file_dir = new File(HiDataValue.getPathCameraSnapshot(mMyCamera.getUid(), this));
                if (!file_dir.exists()) {
                    file_dir.mkdirs();
                }
                String filename = HiTools.getFileNameWithTime(0);
                final String file = file_dir.getAbsoluteFile() + "/" + filename;
                Bitmap frame = mMyCamera != null ? mMyCamera.getSnapshot() : null;
                if (frame != null && HiTools.saveImage(file, frame)) {
                    SaveToPhone(file, filename);
                    Toast toast1 = Toast.makeText(LiveViewActivity.this, getText(R.string.tips_snapshot_success), Toast.LENGTH_SHORT);
                    toast1.show();
                    toastList.add(toast1);
                } else {
                    Toast toast2 = Toast.makeText(LiveViewActivity.this, getText(R.string.tips_snapshot_failed), Toast.LENGTH_SHORT);
                    toast2.show();
                    toastList.add(toast2);
                }
            } else {
                Toast toast3 = Toast.makeText(LiveViewActivity.this, getText(R.string.tips_no_sdcard).toString(), Toast.LENGTH_SHORT);
                toast3.show();
                toastList.add(toast3);
            }
        }
    }


    private void SaveToPhone(final String path, final String fileName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(getContentResolver(), path, fileName, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
            }
        }).start();
    }


    private void handTalking() {
        if (mRecordingState == RECORDING_STATUS_ING) {
            mMyCamera.PausePlayAudio();
        } else {
            mMyCamera.stopListening();
            mVoiceIsTran = false;
        }
        if (isTalking) {
            mMyCamera.stopTalk();
        } else {
            mMyCamera.startTalk();
        }
        if (isListening) {
            mMyCamera.stopListening();
            mVoiceIsTran = false;
            firstTabFragment.iv_listen.setSelected(false);
            iv_landscape_listen.setSelected(false);
            isListening = !isListening;
        }
        isTalking = !isTalking;
        firstTabFragment.iv_duijiang.setSelected(isTalking);
        iv_landscape_talk.setSelected(isTalking);
    }

    private void handRecord() {
        if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
            showAlertDialog();
            return;
        }
        clickRecording();
    }

    //点击录像按钮，保存录像文件
    private void clickRecording() {
        if (mRecordingState == RECORDING_STATUS_NONE) {
            mRecordingState = LiveViewActivity.RECORDING_STATUS_ING;
            TimerRecording();
            iv_landscape_record.setSelected(true);
            firstTabFragment.iv_record.setSelected(true);

            mStartRecoedTime = 0;
            ll_recording.setVisibility(View.VISIBLE);
            iv_recording.setVisibility(View.VISIBLE);
            mRecHandler.sendEmptyMessage(110);
        } else if (mRecordingState == RECORDING_STATUS_ING) {
            mRecordingState = RECORDING_STATUS_NONE;
            if (mVoiceIsTran && !iv_landscape_listen.isSelected()) {
                mMyCamera.stopListening();
                mVoiceIsTran = false;
            }
            mMyCamera.stopRecording();
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (timerTask != null) {
                timerTask.cancel();
                timerTask = null;
            }
            iv_landscape_record.setSelected(false);
            firstTabFragment.iv_record.setSelected(false);

            ll_recording.setVisibility(View.INVISIBLE);
            iv_recording.setVisibility(View.INVISIBLE);
            mRecHandler.removeCallbacksAndMessages(null);
        }
    }

    private void TimerRecording() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        final File cameraFolder = new File(HiDataValue.getPathCameraVideoLocalRecord(mMyCamera.getUid(),this));
        if (!cameraFolder.exists()) {
            cameraFolder.mkdirs();
        }
        timer = new Timer();
        timerTask = new TimerTask() {
            boolean isFirst = true;
            @Override
            public void run() {
                if (mRecordingState == LiveViewActivity.RECORDING_STATUS_ING) {
                    mMyCamera.stopRecording();
                }
                recordFile = cameraFolder.getAbsoluteFile() + "/" + HiTools.getFileNameWithTime(1);
                long available = HiTools.getAvailableSize();
                if (available < 100 && available > 0) {// 设备内存小于100M
                    mHandler.sendEmptyMessage(0X999);
                    return;
                }
                if (isFirst) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mMyCamera.startRecording(recordFile);
                            isFirst = false;
                        }
                    });
                } else {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mMyCamera.startRecording(recordFile);
                        }
                    }, 1000);
                }
            }
        };
        timer.schedule(timerTask, 0, 10 * 60 * 1000);
    }


    private void handVideoQuality(View view, int offsetx) {
        clickRatio((TextView) view, offsetx);
    }

    private void handListening(ImageView v) {
        if (HiDataValue.ANDROID_VERSION >= 6 && (!HiTools.checkPermission(this, Manifest.permission.RECORD_AUDIO) || !HiTools.checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
            showAlertDialog();
            return;
        }
        clickListen();
    }

    private void clickRatio(TextView iv, int offsetx) {
        View customView = getLayoutInflater().inflate(R.layout.popview_resolution_ratio, null, false);
        PopupWindow mPopupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        mPopupWindow.setBackgroundDrawable(cd);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        int location[] = new int[2];
        iv.getLocationOnScreen(location);
        int offsety = HiTools.dip2px(this, 90);
        mPopupWindow.showAtLocation(iv, 0, location[0] - offsetx, location[1] - offsety);
        final TextView ratio_high = customView.findViewById(R.id.ratio_high);
        final TextView ratio_fluent = customView.findViewById(R.id.ratio_fluent);
        int videoQuality = mMyCamera.getVideoQuality();
        Log.i("tedu","---qqqqqq---");
        if (videoQuality == 0) {
            ratio_high.setSelected(true);
            ratio_fluent.setSelected(false);
        } else if (videoQuality == 1) {
            ratio_high.setSelected(false);
            ratio_fluent.setSelected(true);
        }
        Log.i("tedu","---wwwww---");
        ratio_high.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                ratio_high.setSelected(true);
                ratio_fluent.setSelected(false);
                switchVideoQuality(0);
            }
        });

        ratio_fluent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                ratio_fluent.setSelected(true);
                ratio_high.setSelected(false);
                switchVideoQuality(1);
            }
        });
    }

    private void switchVideoQuality(int quality) {
        Log.i("tedu","---eeeee---");
        if (mMyCamera == null) {
            return;
        }
        if (quality == mMyCamera.getVideoQuality()) return;
        Log.i("tedu","---rrrrrr---");
        //处理View
        iv_landscape_record.setSelected(false);
        firstTabFragment.iv_record.setSelected(false);
        ll_recording.setVisibility(View.GONE);
        firstTabFragment.iv_listen.setSelected(false);
        iv_landscape_listen.setSelected(false);
        firstTabFragment.iv_duijiang.setSelected(false);
        iv_landscape_talk.setSelected(false);

        mMyCamera.setVideoQuality(quality);
        mMyCamera.updateInDatabase(LiveViewActivity.this);
        mIsSwitchResolution = true;
        mMyCamera.stopLiveShow();
        mMyCamera.disconnect();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.i("tedu","---TTTT---");
                mMyCamera.connect();
            }
        }, 500);

    }


    // 点击声音按钮开始监听语音，按住喇叭说话，松开接收
    private void clickListen() {
        if (mRecordingState == RECORDING_STATUS_ING) {// 正在录像中...
            if (mVoiceIsTran) {
                mMyCamera.PausePlayAudio();
            } else {
                mMyCamera.stopRecording();
                mMyCamera.startListening();
                mVoiceIsTran = true;
                TimerRecording();
                mStartRecoedTime=0;
            }
            if (isListening) {
                iv_landscape_listen.setSelected(false);
                firstTabFragment.iv_listen.setSelected(false);
            } else {
                iv_landscape_listen.setSelected(true);
                firstTabFragment.iv_listen.setSelected(true);
            }
        } else {
            if (isListening) {
                iv_landscape_listen.setSelected(false);
                firstTabFragment.iv_listen.setSelected(false);
                mMyCamera.stopListening();
                mVoiceIsTran = false;
            } else {
                iv_landscape_listen.setSelected(true);
                firstTabFragment.iv_listen.setSelected(true);
                mMyCamera.startListening();
                mVoiceIsTran = true;
            }
        }
        if (isTalking) {
            firstTabFragment.iv_duijiang.setSelected(false);
            iv_landscape_talk.setSelected(false);
            mMyCamera.stopTalk();
            isTalking = !isTalking;
        }
        isListening = !isListening;
    }


    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(LiveViewActivity.this);
        builder.setMessage(getString(R.string.tips_no_permission));
        builder.setPositiveButton(getString(R.string.setting), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                HiTools.toSelfSetting(LiveViewActivity.this);
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), null);
        builder.show();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {//竖屏
            handPortrait();
        } else {//横屏
            handLandScape();
        }
        mMonitor.setVisibility(View.VISIBLE);//解决魅族5 无视频
    }

    private void handLandScape() {
        secondTabFrament.unRegisterMyCamera();
        mMonitor.setmIsFullScreen(1);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        titleview.setVisibility(View.GONE);
        ll_bottom.setVisibility(View.GONE);
        rl_wrap.setVisibility(View.GONE);
        rl_landscape_view.setVisibility(View.VISIBLE);
        tv_landscape_video_quality.setText(mCameraVideoQuality == 0 ? getString(R.string.high_definition) : getString(R.string.fluent));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight());
        mMonitor.setLayoutParams(params);
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(ll_recording.getLayoutParams());
        params2.setMargins(HiTools.dip2px(this, 20), HiTools.dip2px(this, 55), 0, 0);
        ll_recording.setLayoutParams(params2);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mMonitor.screen_height = dm.heightPixels;
        mMonitor.screen_width = dm.widthPixels;
        initMatrix(mMonitor.screen_width, mMonitor.screen_height);
        mMonitor.setMatrix(mMonitor.left, mMonitor.bottom, mMonitor.width, mMonitor.height);
    }

    private void handPortrait() {
        secondTabFrament.RegisterMyCamera();
        mMonitor.setmIsFullScreen(0);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        titleview.setVisibility(View.VISIBLE);
        ll_bottom.setVisibility(View.VISIBLE);
        rl_wrap.setVisibility(View.VISIBLE);
        rl_landscape_view.setVisibility(View.GONE);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(getWindowManager().getDefaultDisplay().getWidth(), HiTools.dip2px(this, 250));
        mMonitor.setLayoutParams(params);
        if (mIsHaveVirtual) {//做适配
            RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, mDp_250);
            mMonitor.setLayoutParams(param1);
            iv_placeholder.setLayoutParams(param1);
            RelativeLayout.LayoutParams para2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            para2.setMargins(10, HiTools.dip2px(this, 215), 10, 3);
            rl_wrap.setLayoutParams(para2);
        }
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(ll_recording.getLayoutParams());
        params2.setMargins(HiTools.dip2px(this, 12), HiTools.dip2px(this, 5), 0, 0);
        ll_recording.setLayoutParams(params2);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mMonitor.screen_height = dm.heightPixels;
        mMonitor.screen_width = dm.widthPixels;
        initMatrix(mMonitor.screen_width, mDp_250);
        mMonitor.setMatrix(mMonitor.left, mMonitor.bottom, mMonitor.width, mMonitor.height);
    }


    public void showLoadingView() {
        Animation rotateAnim = AnimationUtils.loadAnimation(LiveViewActivity.this, R.anim.rotate);
        mIvLoading2.setVisibility(View.VISIBLE);
        mIvLoading2.startAnimation(rotateAnim);
    }

    public void dismissLoadingView() {
        mIvLoading2.clearAnimation();
        mIvLoading2.setVisibility(View.GONE);
    }

    public void showPlaceLoadingView() {
        Animation rotateAnim = AnimationUtils.loadAnimation(LiveViewActivity.this, R.anim.rotate);
        iv_placeholder_rotate.setVisibility(View.VISIBLE);
        iv_placeholder_rotate.startAnimation(rotateAnim);
        iv_placeholder.setVisibility(View.VISIBLE);
    }

    public void dismissPlaceLoadingView() {
        if (iv_placeholder_rotate.getAlpha() == 1.0f) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(iv_placeholder_rotate, "Alpha", 1f, 0f);
            animator.setDuration(600);
            animator.setStartDelay(900);
            animator.start();
        }
        if (iv_placeholder.getAlpha() == 1.0f) {
            ObjectAnimator animator1 = ObjectAnimator.ofFloat(iv_placeholder, "Alpha", 1f, 0f);
            animator1.setDuration(600);
            animator1.setStartDelay(900);
            animator1.start();
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.sb_brightness:
                if (tv_brightness != null) {
                    tv_brightness.setText(seekBar.getProgress() + "");
                }
                break;
            case R.id.sb_contrast:
                if (tv_contrast != null) {
                    tv_contrast.setText(seekBar.getProgress() + "");
                }
                break;
            case R.id.sb_saturation:
                if (tv_saturation != null) {
                    tv_saturation.setText(seekBar.getProgress() + "");
                }
                break;
        }

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        switch (seekBar.getId()) {
            case R.id.sb_brightness:
                display_param.u32Brightness = seekBar.getProgress();
                showjuHuaDialog();
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_DISPLAY_PARAM, display_param.parseContent());
                break;
            case R.id.sb_contrast:
                display_param.u32Contrast = seekBar.getProgress();
                showjuHuaDialog();
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_DISPLAY_PARAM, display_param.parseContent());
                break;
            case R.id.sb_saturation:
                display_param.u32Saturation = seekBar.getProgress();
                showjuHuaDialog();
                mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_DISPLAY_PARAM, display_param.parseContent());
                break;
        }
    }

    private void setViewWhetherClick(boolean whetherClick) {
        if (firstTabFragment == null || secondTabFrament == null) return;
        iv_landscape_listen.setClickable(whetherClick);
        firstTabFragment.iv_listen.setClickable(whetherClick);
        iv_landscape_record.setClickable(whetherClick);
        firstTabFragment.iv_record.setClickable(whetherClick);
        iv_land_snapshot.setClickable(whetherClick);
        firstTabFragment.iv_snapshot.setClickable(whetherClick);
        iv_landscape_talk.setClickable(whetherClick);
        firstTabFragment.iv_duijiang.setClickable(whetherClick);

        secondTabFrament.ll_jxfz.setClickable(whetherClick);
        secondTabFrament.ll_jjjj.setClickable(whetherClick);
        secondTabFrament.ll_yzw.setClickable(whetherClick);
        secondTabFrament.ll_ylkz.setClickable(whetherClick);
        secondTabFrament.ll_txtj.setClickable(whetherClick);
    }


}










